import { Feature } from "ol";
import { Vector as VectorLayer } from "ol/layer";
import { Vector as VectorSource } from "ol/source";
import { LineString, Point, MultiLineString, Polygon } from "ol/geom";
import { Fill, Stroke, Style, Icon, Text, Circle } from "ol/style";
import { transform, fromLonLat } from "ol/proj";
import Overlay from 'ol/Overlay'
import featureObj from "./feature";
export default {
  data() {
    return {
      typhoonPathLayer: null, // 台风路径图层
      typhoonPathSource: null, // 台风路径数据源
      typhoonDynamicPathLayer: null, // 台风轨迹图层
      typhoonDynamicPathSource: null, // 台风轨迹数据源
      lastSolarFeature: null, // 记录上一个台风风圈
      lastPointFeature: null, // 记录上一个被放大的点
      typhoonInfo: {}, // 台风点详情
      overlay: null, // 叠加层实例
    };
  },
  methods: {
    // 地图缩小
    zoomOut() {
      const view = this.map.getView();
      const zoom = view.getZoom();
      view.setZoom(zoom - 1);
    },
    // 地图缩小
    zoomIn() {
      const view = this.map.getView();
      const zoom = view.getZoom();
      view.setZoom(zoom + 1);
    },
    // 获取台风路径数据
    drawTyphoonPath() {
      // 清除所有要素
      if (this.typhoonPathSource) this.typhoonPathSource.clear();
      // 删除所在图层
      if (this.typhoonPathLayer) this.map.removeLayer(this.typhoonPathLayer);
      this.typhoonPathLayer = null;
      fetch("./json/typhoon-songda.json")
        .then((rsp) => {
          return rsp.json();
        })
        .then((data) => {
          const { points } = data;
          let features = [];
          let positons = [];
          console.log(points);
          points.forEach((i, index) => {
            let positon = [i.lng, i.lat];
            // 在ol里放置点要素
            let featurePoint = new Feature({
              geometry: new Point(transform(positon, "EPSG:4326", "EPSG:3857")), // 将经纬度坐标系，转换为投影坐标系
            });
            featurePoint.setStyle(
              new Style({
                image: new Circle({
                  fill: new Fill({
                    color: this.judgeColorByTyphoonLevel(i.strong),
                  }),
                  radius: 4,
                }),
              })
            );
            featurePoint.set("type", "typhoonPoint");
            featurePoint.set("point", i)
            features.push(featurePoint);
            // 在ol里放置线要素
            if (index !== points.length - 1) {
              let nextPositon = [points[index + 1].lng, points[index + 1].lat];
              positons.push([fromLonLat(positon), fromLonLat(nextPositon)]);
            }
          });
          // 利用MultiLineString画线
          let featureLine = new Feature({
            geometry: new MultiLineString(positons),
          });
          featureLine.setStyle(
            new Style({
              stroke: new Stroke({
                color: "yellow",
                width: 4,
              }),
            })
          );
          features.push(featureLine);
          // 矢量数据源
          this.typhoonPathSource = new VectorSource();
          this.typhoonPathSource.addFeatures(features);
          // 矢量图层
          this.typhoonPathLayer = new VectorLayer();
          this.typhoonPathLayer.setSource(this.typhoonPathSource);
          this.map.addLayer(this.typhoonPathLayer);
        });
    },
    // 根据台风等级判断各个点的颜色
    judgeColorByTyphoonLevel(level) {
      let map = {
        热带风暴: "red",
        热带低压: "blue",
        强热带风暴: "green",
        台风: "orange",
        强台风: "yellow",
        超强台风: "salmon",
      };
      return map[level];
    },
    // 画出台风路径 interval版本
    drawTyphoonPathInterval(showSolar = false) {
      // 清除所有要素
      if (this.typhoonDynamicPathSource) this.typhoonDynamicPathSource.clear();
      // 删除图层
      if (this.typhoonDynamicPathLayer)
        this.map.removeLayer(this.typhoonDynamicPathLayer);
      this.typhoonDynamicPathLayer = null;
      fetch("./json/typhoon-aere.json")
        .then((rsp) => {
          return rsp.json();
        })
        .then((data) => {
          const { points } = data;
          let index = 0;
          this.typhoonDynamicPathSource = new VectorSource();
          this.typhoonDynamicPathLayer = new VectorLayer();
          this.typhoonDynamicPathLayer.setSource(this.typhoonDynamicPathSource);
          let timer = setInterval(() => {
            if (index === points.length - 1) {
              clearInterval(timer);
            }
            let positon = [points[index].lng, points[index].lat];
            // 添加要素点
            let featurePoint = new Feature({
              geometry: new Point(fromLonLat(positon)),
            });
            featurePoint.setStyle(
              new Style({
                image: new Circle({
                  fill: new Fill({
                    color: this.judgeColorByTyphoonLevel(points[index].strong),
                  }),
                  radius: 4,
                }),
              })
            );
            featurePoint.set("type", "typhoonPoint");
            featurePoint.set("point", points[index])
            this.typhoonDynamicPathSource.addFeature(featurePoint);
            // 添加要素连线
            if (index > 0) {
              let lastPositon = [points[index - 1].lng, points[index - 1].lat];
              let featureLine = new Feature({
                geometry: new LineString([
                  fromLonLat(positon),
                  fromLonLat(lastPositon),
                ]),
              });
              this.typhoonDynamicPathSource.addFeature(featureLine);
            }
            // 添加要素(台风风圈)
            if (showSolar && points[index].radius7) {
              let featureSolar = this.drawSolar(points[index]);
              if (this.lastSolarFeature) {
                this.typhoonDynamicPathSource.removeFeature(
                  this.lastSolarFeature
                );
              }
              this.lastSolarFeature = featureSolar;
              this.lastSolarFeature.set('type', 'typhoonSolar')
              this.typhoonDynamicPathSource.addFeature(featureSolar);
            }
            index++;
          }, 100);
          this.map.addLayer(this.typhoonDynamicPathLayer);
        });
    },
    // 画风圈
    drawSolar(points) {
      let radiusArr = points.radius7.split("|").map((i) => parseFloat(i));
      // 数据格式
      var Configs = {
        CIRCLE_CENTER_X: parseFloat(points.lng),
        CIRCLE_CENTER_Y: parseFloat(points.lat),
        CIRCLE_R: {
          SE: radiusArr[0] / 100, // 控制风圈大小
          NE: radiusArr[1] / 100,
          NW: radiusArr[2] / 100,
          SW: radiusArr[3] / 100,
        },
      };
      const _interval = 6;
      const positons = [];
      for (var i = 0; i < 360 / _interval; i++) {
        var _r = 0;
        var _ang = i * _interval;
        if (_ang > 0 && _ang <= 90) {
          _r = Configs.CIRCLE_R.NE;
        } else if (_ang > 90 && _ang <= 180) {
          _r = Configs.CIRCLE_R.NW;
        } else if (_ang > 180 && _ang <= 270) {
          _r = Configs.CIRCLE_R.SW;
        } else {
          _r = Configs.CIRCLE_R.SE;
        }

        var x = Configs.CIRCLE_CENTER_X + _r * Math.cos((_ang * 3.14) / 180);
        var y = Configs.CIRCLE_CENTER_Y + _r * Math.sin((_ang * 3.14) / 180);
        positons.push(fromLonLat([x, y]));
      }
      let feature = new Feature({
        geometry: new Polygon([positons]),
      });
      return feature;
    },
    // 注册一个hover事件
    designHoverOnMap() {
      this.map.on("pointermove", (ev) => {
        let pixel = ev.pixel;
        let feature = this.map.forEachFeatureAtPixel(pixel, (feature) => {
          return feature;
        });
        if (feature) {
          let execName = featureObj.tyepJudge(feature) + 'Hover'
          featureObj[execName].apply(this, [feature])
        } else {
          this.map.getTargetElement().style.cursor = "";
          if (this.lastPointFeature) {
            this.lastPointFeature.getStyle().getImage().setRadius(4);
            this.lastPointFeature.changed();
          }
          this.overlay && this.overlay.setPosition(undefined) // 叠加层隐藏
        }
      });
    },
    // 添加叠加层
    addOverlay: function(points) {
      this.overlay = new Overlay({
       element: this.$refs.typhoonInfo.$el,
       autoPan: true,
       autoPanAnimation: {
        duration: 250
       }
      })
      this.overlay.setPosition(undefined)
      this.map.addOverlay(this.overlay)
    }
  },
};
